/**
 * 上海交大--鹏越惊虹
 */
package org.infosec.lc.exercises.jdk6Features;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsServer;

/**
 * 作者：林超 <br>
 * 时间：2011-12-26 下午03:59:52 <br>
 * 完整类名：org.infosec.lc.exercises.jdk6Features.HttpServerApi <br>
 * 说明：Http Server API. JDK6提供了一个简单的Http Server API,据此我们可以构建自己的嵌入式Http
 * Server,它支持Http和Https协议,提供了HTTP1.1的部分实现，没有被实现的那部分可以通过扩展已有的Http Server
 * API来实现,程序员必须自己实现HttpHandler接口
 * ,HttpServer会调用HttpHandler实现类的回调方法来处理客户端请求,在这里,我们把一个Http请求和它的响应称为一个交换
 * ,包装成HttpExchange类,HttpServer负责将HttpExchange传给
 * HttpHandler实现类的回调方法.下面代码演示了怎样创建自己的Http Server .<br>
 * <br>
 * POM.xml<br>
 * <br>
 */
public class HttpServerApi {

	/**
	 * 说明：<br>
	 * 参数：<br>
	 * 
	 * @param args
	 */
	private static int count = 0;

	public static void main(String[] args) {
		try {
			HttpServer hs = HttpServer.create(new InetSocketAddress(8888), 0);
			hs.createContext("/", new MyHandler());
			hs.createContext("/java", new MyHandlerJava());
			hs.setExecutor(null);
			hs.start();
			System.out.println("---begin---");
			System.out.println("Listening on " + hs.getAddress());
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	static class MyHandler implements HttpHandler {
		public void handle(HttpExchange he) throws IOException {
			System.out.println("Request " + count++);
			System.out.println(he.getHttpContext().getPath());

			InputStream is = he.getRequestBody();
			String response = "<font color='blue'>Happy Spring Festerval-</font><a href='https://localhost:8443/manager-web'>dg</a>";
			he.sendResponseHeaders(200, response.length());
			OutputStream os = he.getResponseBody();
			os.write(response.getBytes());
			os.close();
		}
	}
	static class MyHandlerJava implements HttpHandler {
		public void handle(HttpExchange he) throws IOException {
			System.out.println("Request " + count++);
			System.out.println(he.getHttpContext().getPath());
			
			InputStream is = he.getRequestBody();
			String response = "<font color='blue'>Happy Spring Festerval-----java</font>";
			he.sendResponseHeaders(200, response.length());
			OutputStream os = he.getResponseBody();
			os.write(response.getBytes());
			os.close();
		}
	}
}
